/* Copyright (C) 2008 Lorenzo Braghetto
 * 
 * This file is part of BatteryDiff Widget.
 * 
 *   BatteryDiff Widget is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *   
 *  BatteryDiff Widget is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
*/

package com.mono.diffwidget;

import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;

public class BatteryDiffWidget extends AppWidgetProvider {
	public static final String PREFS_NAME = "DiffWidgetPrefs";
	public static final String PREFS_NAME2 = "TimePref";
	public static int refresh = 0;
	public static int iter = 0;
	public boolean config = false;
	public static String hours = "";
	public static String minutes = "";
	public static double battdiff1;
	public static double battdiff2;

	@Override
	public void onUpdate(Context context, AppWidgetManager manager,
			int[] appWidgetIds) {
        super.onUpdate(context, manager, appWidgetIds);
		// Clear Battery Stats
		SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.clear();
		editor.commit();
		
		Intent service = new Intent(context,
				BatteryDiffService.class);
		PendingIntent christmas = PendingIntent.getService(
				context, 0, service, 0);

		SharedPreferences settings2 = context.getSharedPreferences(PREFS_NAME2,
				0);
		
		AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
		alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
				settings2.getInt("time", 2) * 60 * 1000, christmas);

		final int length = appWidgetIds.length;
		for (int i = 0; i < length; i++) {
			int appWidgetId = appWidgetIds[i];
			RemoteViews views = buildView(context, "Wait");
			manager.updateAppWidget(appWidgetId, views);
		}

	}

	public void onDelete(Context context, int[] appWidgetIds) {
		SharedPreferences settings3 = context.getSharedPreferences(PREFS_NAME,
				0);
		SharedPreferences.Editor editor3 = settings3.edit();
		editor3.clear();
		editor3.commit();
		SharedPreferences settings4 = context.getSharedPreferences(PREFS_NAME2,
				0);
		SharedPreferences.Editor editor4 = settings4.edit();
		editor4.clear();
		editor4.commit();
		Page.cancelAlarm(context);
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		;
		mNotificationManager.cancelAll();
	}

	public static RemoteViews buildView(Context context, String answer) {
		RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);
		views.setTextViewText(R.id.condition, answer);
		Intent defineIntent2 = new Intent(context, About.class);
		PendingIntent pendingIntent2 = PendingIntent.getActivity(context,
				0 /* no requestCode */, defineIntent2, 0 /* no flags */);
		views.setOnClickPendingIntent(R.id.widget, pendingIntent2);

		return views;
	}

	public static String text(Context context, int currentBatteryLevel) {// Main
																			// algorithm
		int start = 0;
		int lastBatterycheck[];
		int n = 0;
		int battdiff = 0;
		String text = "";
		SharedPreferences settings = context
				.getSharedPreferences(PREFS_NAME, 0);
		int check = settings.getInt("check", -1);
		SharedPreferences settingz = context.getSharedPreferences(PREFS_NAME2,
				0);
		refresh = settingz.getInt("time", 0);
		if (refresh == 1)
			iter = 60;
		if (refresh == 2)
			iter = 30;
		if (refresh == 3)
			iter = 20;

		lastBatterycheck = new int[iter + 1];

		if (currentBatteryLevel != 0) {
			SharedPreferences.Editor editor = settings.edit();

			check = check + 1;
			editor.putInt(String.valueOf(check), currentBatteryLevel);
			editor.putInt("check", check);
			editor.commit();
			if (check > 0) {
				if (check < (iter + 1)) {
					start = 0;
				} else {
					start = check - iter;
				}
				int i = 0;
				for (int z = start; z <= check; z++) {
					lastBatterycheck[i] = settings.getInt(String.valueOf(z), 0);
					i++;
				}
				for (int x = 1; x < i; x++) {
					battdiff = battdiff + lastBatterycheck[x - 1]
							- lastBatterycheck[x];
					if (n == (iter / 2)) {
						battdiff1 = battdiff;
					}
					n = n + 1;
				}
				if (n == iter) {
					battdiff2 = battdiff - battdiff1;
					if (battdiff1 < battdiff2 / 3) {
						flush(check, iter, context);
					}
				}
			}
			if (battdiff > 0) {
				float timeMillis = ((float) currentBatteryLevel / (float) battdiff)
						* (n) * refresh * 60 * 1000;

				float time = timeMillis / 1000;

				minutes = Integer.toString((int) ((time % 3600) / 60));
				hours = Integer.toString((int) (time / 3600));
				for (int i = 0; i < 2; i++) {
					if (minutes.length() < 2) {
						minutes = "0" + minutes;
					}
					if (hours.length() < 2) {
						hours = "0" + hours;
					}
				}
				text = hours + "h " + minutes + "m";
				editor.putString("minuti", minutes);
				editor.putString("ore", hours);
			} else {
				text = "Wait";
			}
			editor.putString("text", text);
			editor.putFloat("tempo", n * refresh);
			editor.putFloat("battdiff", battdiff);
			editor.commit();
		}
		return text;
	}

	public static void flush(int check, int iter, Context context) {
		int b = 0;
		int start = check - (iter / 2);
		SharedPreferences settings = context
				.getSharedPreferences(PREFS_NAME, 0);
		SharedPreferences.Editor editor = settings.edit();
		for (int i = start, z = 0; i < check && z < (iter / 2); i++, z++) {
			b = settings.getInt(String.valueOf(i), 0);
			editor.putInt(String.valueOf(z), b);
		}
		editor.putInt("check", (iter / 2));
		editor.commit();
	}
}
